package com.iflytek.jcy.supervise.job.component.fdfs;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2022/1/19
 */
@Component
public class FDFSHelper {
    protected final Logger logger = LoggerFactory.getLogger(FDFSHelper.class);

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    public String uploadFile(MultipartFile file) throws IOException {
        if (file != null) {
            byte[] bytes = file.getBytes();
            long fileSize = file.getSize();
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            return this.uploadFile(bytes, fileSize, extension);
        }
        return null;
    }

    /**
     * 文件上传
     *
     * @param file 待上传文件
     *
     * @return 返回文件路径（卷名和文件名）
     */
    public String uploadFile(File file) throws IOException {
        if (file == null || !file.exists() || !file.isFile() || !file.canRead() || file.length() == 0) {
            logger.info("文件不存在 或者 不可读 或者 为空, file: {}", file.getAbsolutePath());
            return null;
        }

        // 元数据
        Set<MetaData> metaDataSet = new HashSet<MetaData>();
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));
        metaDataSet.add(new MetaData("from", "supervise-job-web"));
        metaDataSet.add(new MetaData("size", String.valueOf(file.length())));

        try (FileInputStream fis = new FileInputStream(file)) {
            String extension = FilenameUtils.getExtension(file.getName());
            StorePath storePath = fastFileStorageClient.uploadFile(fis, file.length(), extension, metaDataSet);
            return storePath.getFullPath();
        }
    }

    /**
     * 文件上传
     *
     * @param inputStream 输入流
     * @param fileSize    文件大小
     * @param extension   文件扩展名
     *
     * @return 返回文件路径（卷名和文件名）
     */
    public String uploadFile(InputStream inputStream, long fileSize, String extension) {
        // 元数据
        Set<MetaData> metaDataSet = new HashSet<MetaData>();
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));
        metaDataSet.add(new MetaData("from", "supervise-job-web"));
        try {
            metaDataSet.add(new MetaData("size", String.valueOf(inputStream.available())));
        }
        catch (IOException e) {
            //
        }
        StorePath storePath = fastFileStorageClient.uploadFile(inputStream, fileSize, extension, metaDataSet);
        return storePath.getFullPath();
    }

    /**
     * 文件上传
     *
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     *
     * @return 返回文件路径（卷名和文件名）
     */
    public String uploadFile(byte[] bytes, long fileSize, String extension) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        // 元数据
        Set<MetaData> metaDataSet = new HashSet<MetaData>();
        metaDataSet.add(new MetaData("dateTime", LocalDateTime.now().toString()));
        metaDataSet.add(new MetaData("from", "supervise-job-web"));
        metaDataSet.add(new MetaData("size", String.valueOf(bytes.length)));
        StorePath storePath = fastFileStorageClient.uploadFile(bais, fileSize, extension, metaDataSet);
        return storePath.getFullPath();
    }

    /**
     * 下载文件
     *
     * @param filePath 文件路径
     *
     * @return 文件字节
     *
     * @throws IOException
     */
    public byte[] downloadFile(String filePath) throws IOException {
        byte[] bytes = null;
        if (StringUtils.isNotBlank(filePath)) {
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            DownloadByteArray byteArray = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, path, byteArray);
        }
        return bytes;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public void deleteFile(String filePath) {
        if (StringUtils.isNotBlank(filePath)) {
            fastFileStorageClient.deleteFile(filePath);
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public void deleteFileQuietly(String filePath) {
        if (StringUtils.isNotBlank(filePath)) {
            try {
                fastFileStorageClient.deleteFile(filePath);
            }
            catch (Throwable e) {
                logger.warn("fastDFS文件删除失败. path: {}", filePath, e);
            }
        }
    }

}